#!/bin/bash

source $HOME/.bashrc && conda activate lxb39 && cd $PROJECTS/MoE-LLaVA

gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
IFS=',' read -ra GPULIST <<< "$gpu_list"

CHUNKS=${#GPULIST[@]}

CONV="phi"
CKPT_NAME="moe-llava-clip-336-phi-2.7b-3rd-sft-moe-reproduce"
CKPT="$OUTPUTS/MoE-LLaVA/${CKPT_NAME}"
SPLIT="llava_gqa_testdev_balanced"
EVAL="eval_files"

mkdir -p ${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}
for IDX in $(seq 0 $((CHUNKS-1))); do
    deepspeed --include localhost:${GPULIST[$IDX]} --master_port $((${GPULIST[$IDX]} + 23333)) moellava/eval/model_vqa_loader.py \
        --model-path ${CKPT} \
        --question-file ${EVAL}/gqa/$SPLIT.jsonl \
        --image-folder ${EVAL}/gqa/data/images \
        --answers-file ${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}/${CHUNKS}_${IDX}.jsonl \
        --num-chunks $CHUNKS \
        --chunk-idx $IDX \
        --temperature 0 \
        --conv-mode ${CONV} &
done

wait

output_file=${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}/merge.jsonl

# Clear out the output file if it exists.
> "$output_file"

# Loop through the indices and concatenate each file.
for IDX in $(seq 0 $((CHUNKS-1))); do
    cat ${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}/${CHUNKS}_${IDX}.jsonl >> "$output_file"
done

python3 scripts/convert_gqa_for_eval.py --src $output_file --dst ${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}/testdev_balanced_predictions.json

python3 moellava/eval/eval_gqa.py --tier ${EVAL}/gqa/answers/$SPLIT/${CKPT_NAME}/testdev_balanced \
                                  --questions ${EVAL}/gqa/data/testdev_balanced_questions.json

